package com.chen.authority.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.chen.authority.common.annotation.Log;
import com.chen.authority.common.enums.BusinessType;
import com.chen.authority.common.response.PageResponse;
import com.chen.authority.common.model.PageQo;
import com.chen.authority.service.CodeGenerateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author chengy
 * @date 2022/11/19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tool/code-generate")
@Api(tags = "代码生成 CodeGenerateController")
public class CodeGenerateController {

    private final CodeGenerateService codeGenerateService;

    @GetMapping("/list")
    @ApiOperation("获取数据表列表")
    @SaCheckPermission("tool:code-generate:list")
    public PageResponse<Map<String, Object>> list(PageQo pageQo, String name, String description) {
        return PageResponse.success(codeGenerateService.pageQueryTableList(pageQo, name, description));
    }

    @GetMapping
    @ApiOperation("生成代码")
    @SaCheckPermission("tool:code-generate:gen")
    @Log(module = "系统工具-代码生成", businessType = BusinessType.GENERATE)
    public void code(@ApiParam("生成表名") String[] names, HttpServletResponse response) throws IOException {
        byte[] data = codeGenerateService.generateCode(names);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
